package com.next.network.tcp;

import com.next.network.ChannelMap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.util.Random;

public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {

    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)  {
        System.out.println("服务端接收到tcp客户端消息："+msg);
        ChannelMap.put("tcp", ctx.channel());
        ctx.writeAndFlush(msg);

        //发送消息给ws端
        Channel wsChannel = ChannelMap.get("ws");
        wsChannel.writeAndFlush(new TextWebSocketFrame("来自tcp端发送的消息" + new Random().nextInt()));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)  {
        cause.printStackTrace();
    }
}
